package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.*;
import cn.hutool.log.StaticLog;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.constant.CacheNames;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.service.DeptService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.DataBaseHelper;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.TreeBuildUtils;
import com.ruoyi.common.utils.redis.CacheUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.bank.*;
import com.ruoyi.system.domain.bo.*;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysDeptService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * 部门管理 服务实现
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Service
public class SysDeptServiceImpl implements ISysDeptService, DeptService {

    private final SysDeptMapper baseMapper;
    private final SysRoleMapper roleMapper;
    private final SysUserMapper userMapper;
    private RestTemplate restTemplate;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    public List<SysDept> selectDeptList(SysDept dept) {
        LambdaQueryWrapper<SysDept> lqw = new LambdaQueryWrapper<>();

        lqw.eq(SysDept::getDelFlag, "0")
            .eq(ObjectUtil.isNotNull(dept.getDeptId()), SysDept::getDeptId, dept.getDeptId())
            .eq(ObjectUtil.isNotNull(dept.getParentId()), SysDept::getParentId, dept.getParentId())
            .like(StringUtils.isNotBlank(dept.getDeptName()), SysDept::getDeptName, dept.getDeptName())
            .eq(StringUtils.isNotBlank(dept.getStatus()), SysDept::getStatus, dept.getStatus())
            .orderByAsc(SysDept::getParentId)
            .orderByAsc(SysDept::getOrderNum);
        return baseMapper.selectDeptList(lqw);
    }

    /**
     * 查询部门树结构信息
     *
     * @param dept 部门信息
     * @return 部门树信息集合
     */
    @Override
    public List<Tree<Long>> selectDeptTreeList(SysDept dept) {
        List<SysDept> depts = this.selectDeptList(dept);
        return buildDeptTreeSelect(depts);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<Tree<Long>> buildDeptTreeSelect(List<SysDept> depts) {
        if (CollUtil.isEmpty(depts)) {
            return CollUtil.newArrayList();
        }
        return TreeBuildUtils.build(depts, (dept, tree) ->
            tree.setId(dept.getDeptId())
                .setParentId(dept.getParentId())
                .setName(dept.getDeptName())
                .setWeight(dept.getOrderNum()));
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Long> selectDeptListByRoleId(Long roleId) {
        SysRole role = roleMapper.selectById(roleId);
        return baseMapper.selectDeptListByRoleId(roleId, role.getDeptCheckStrictly());
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Cacheable(cacheNames = CacheNames.SYS_DEPT, key = "#deptId")
    @Override
    public SysDept selectDeptById(Long deptId) {
        SysDept dept = baseMapper.selectById(deptId);
        if (ObjectUtil.isNull(dept)) {
            return null;
        }
        SysDept parentDept = baseMapper.selectOne(new LambdaQueryWrapper<SysDept>()
            .select(SysDept::getDeptName).eq(SysDept::getDeptId, dept.getParentId()));
        dept.setParentName(ObjectUtil.isNotNull(parentDept) ? parentDept.getDeptName() : null);
        return dept;
    }

    /**
     * 通过部门ID查询部门名称
     *
     * @param deptIds 部门ID串逗号分隔
     * @return 部门名称串逗号分隔
     */
    @Override
    public String selectDeptNameByIds(String deptIds) {
        List<String> list = new ArrayList<>();
        for (Long id : StringUtils.splitTo(deptIds, Convert::toLong)) {
            SysDept dept = SpringUtils.getAopProxy(this).selectDeptById(id);
            if (ObjectUtil.isNotNull(dept)) {
                list.add(dept.getDeptName());
            }
        }
        return String.join(StringUtils.SEPARATOR, list);
    }

    /**
     * 根据ID查询所有子部门数（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public long selectNormalChildrenDeptById(Long deptId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<SysDept>()
            .eq(SysDept::getStatus, UserConstants.DEPT_NORMAL)
            .apply(DataBaseHelper.findInSet(deptId, "ancestors")));
    }

    /**
     * 是否存在子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId) {
        return baseMapper.exists(new LambdaQueryWrapper<SysDept>()
            .eq(SysDept::getParentId, deptId));
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        return userMapper.exists(new LambdaQueryWrapper<SysUser>()
            .eq(SysUser::getDeptId, deptId));
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean checkDeptNameUnique(SysDept dept) {
        boolean exist = baseMapper.exists(new LambdaQueryWrapper<SysDept>()
            .eq(SysDept::getDeptName, dept.getDeptName())
            .eq(SysDept::getParentId, dept.getParentId())
            .ne(ObjectUtil.isNotNull(dept.getDeptId()), SysDept::getDeptId, dept.getDeptId()));
        return !exist;
    }

    /**
     * 校验部门是否有数据权限
     *
     * @param deptId 部门id
     */
    @Override
    public void checkDeptDataScope(Long deptId) {
        if (!LoginHelper.isAdmin()) {
            SysDept dept = new SysDept();
            dept.setDeptId(deptId);
            List<SysDept> depts = this.selectDeptList(dept);
            if (CollUtil.isEmpty(depts)) {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int insertDept(SysDept dept) {
        SysDept info = baseMapper.selectById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new ServiceException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + StringUtils.SEPARATOR + dept.getParentId());
        return baseMapper.insert(dept);
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @CacheEvict(cacheNames = CacheNames.SYS_DEPT, key = "#dept.deptId")
    @Override
    public int updateDept(SysDept dept) {

        SysDept newParentDept = baseMapper.selectById(dept.getParentId());
        SysDept oldDept = baseMapper.selectById(dept.getDeptId());
        if (ObjectUtil.isNotNull(newParentDept) && ObjectUtil.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + StringUtils.SEPARATOR + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = baseMapper.updateById(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
            && !StringUtils.equals(UserConstants.DEPT_NORMAL, dept.getAncestors())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept) {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        baseMapper.update(null, new LambdaUpdateWrapper<SysDept>()
            .set(SysDept::getStatus, UserConstants.DEPT_NORMAL)
            .in(SysDept::getDeptId, Arrays.asList(deptIds)));
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = baseMapper.selectList(new LambdaQueryWrapper<SysDept>()
            .apply(DataBaseHelper.findInSet(deptId, "ancestors")));
        List<SysDept> list = new ArrayList<>();
        for (SysDept child : children) {
            SysDept dept = new SysDept();
            dept.setDeptId(child.getDeptId());
            dept.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
            list.add(dept);
        }
        if (CollUtil.isNotEmpty(list)) {
            if (baseMapper.updateBatchById(list)) {
                list.forEach(dept -> CacheUtils.evict(CacheNames.SYS_DEPT, dept.getDeptId()));
            }
        }
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @CacheEvict(cacheNames = CacheNames.SYS_DEPT, key = "#deptId")
    @Override
    public int deleteDeptById(Long deptId) {
        return baseMapper.deleteById(deptId);
    }

    //https://uatiam.funyard-hotels.com/idp/oauth2/getToken?client_id=AIOERP&grant_type=authorization_code&code=37295329a05c9bfc998c2046bfa6f9cd&client_secret=3c45500e3cd246f99cb2918d423fab01
    @Override
    public void add(String json) {
        baseMapper.add(json);
    }


    @Override
    public String select1() {
        String url = "https://iam.funyard-hotels.com/hotelService/user/addOrModifyUser";
        try {
            List<REQUESTINFO> select = baseMapper.select();
            for (REQUESTINFO selectList : select) {
                List<REQUESTINFO> list = new ArrayList();
                list.add(selectList);
                IS_ESBINFO isEsbinfo = new IS_ESBINFO();
                isEsbinfo.setINSTID(IdUtil.simpleUUID());
                isEsbinfo.setREQUESTTIME(DateUtil.now());
                isEsbinfo.setATTR3("BC_FYAIO");
                Map map = new HashMap();
                map.put("IS_ESBINFO", isEsbinfo);
                map.put("REQUESTINFO", list);
                Console.log("请求参数:{}",JSONUtil.toJsonStr(map));
                String json = JSONUtil.toJsonStr(map);
                String result2 = HttpRequest.post(url)
                    .header("sign", "120477CF4AB2A6044099ED007E483259BF4FD3ED30C2B35CF293EB2EBAB22421")
                    .body(JSONUtil.toJsonStr(json))
                    .timeout(200000)//超时，毫秒
                    .execute().body();
                Console.log("响应参数:{}", result2);
                baseMapper.GlTempEmployeeUpdate(result2,selectList.getId(),JSONUtil.toJsonStr(map));
//                Thread.sleep(1000*1);


            }

                return "success";
            }catch(Exception e){
                e.printStackTrace();
                return "error";
            }



        }


    @Override
    public List<REQUESTINFO> select() {
        return baseMapper.select();
    }

    @Override
    public String addOrUpdateExternalUser() {
        String url = "https://uatiam.funyard-hotels.com/hotelService/user/addOrUpdateExternalUser";
        try {
            List<OrUpdateExternalUser> selectList = baseMapper.addOrUpdateExternalUser1();
            for (OrUpdateExternalUser selectList1 : selectList) {
                List<OrUpdateExternalUser> list = new ArrayList();
                list.add(selectList1);
                IS_ESBINFO isEsbinfo = new IS_ESBINFO();

                isEsbinfo.setINSTID(IdUtil.simpleUUID());
                isEsbinfo.setREQUESTTIME(DateUtil.now());
                isEsbinfo.setATTR3("BC_FYIAM");
                Map map = new HashMap();
                map.put("IS_ESBINFO", isEsbinfo);

                map.put("REQUESTINFO", list);
                Console.log("请求参数:{}", JSONUtil.toJsonStr(map));
                String json = JSONUtil.toJsonStr(map);
                String result2 = HttpRequest.post(url)
                    .header("sign", "120477CF4AB2A6044099ED007E483259BF4FD3ED30C2B35CF293EB2EBAB22421")
                    .body(JSONUtil.toJsonStr(json))
                    .timeout(200000)//超时，毫秒
                    .execute().body();
                Console.log("响应参数:{}", result2);
                baseMapper.OrUpdateExternalUserUpdate(selectList1.getId());

            }
            return "success";
        }catch(Exception e){
            e.printStackTrace();
            return "error";
        }

    }

    @Override
    public List<HrPositionTemp> selectHrPositionTemp() {
        return baseMapper.selectHrPositionTemp();
    }

    @Override
    public String selectHrPositionTemps() {
        String url = "https://iam.funyard-hotels.com/hotelService/position/addOrModifyPosition";
        try {

            List<HrPositionTemp> selectList = baseMapper.selectHrPositionTemp();
            for (HrPositionTemp selectList1 : selectList) {
                List<HrPositionTemp> list = new ArrayList();
                list.add(selectList1);
                IS_ESBINFO isEsbinfo = new IS_ESBINFO();
                isEsbinfo.setINSTID(IdUtil.simpleUUID());
                isEsbinfo.setREQUESTTIME(DateUtil.now());
                isEsbinfo.setATTR3("BC_FYIAM");
                Map map = new HashMap();
                map.put("IS_ESBINFO", isEsbinfo);
                map.put("REQUESTINFO", list);
                Console.log("请求参数:{}", JSONUtil.toJsonStr(map));
                String json = JSONUtil.toJsonStr(map);
                String result2 = HttpRequest.post(url)
                    .header("sign", "120477CF4AB2A6044099ED007E483259BF4FD3ED30C2B35CF293EB2EBAB22421")
                    .body(JSONUtil.toJsonStr(json))
                    .timeout(200000)//超时，毫秒
                    .execute().body();
                Console.log("响应参数:{}", result2);
                baseMapper.updateSelectHrPositionTemp(selectList1.getZPOST(),JSONUtil.toJsonStr(map),result2);

            }
            return "success";
        }catch(Exception e){
            e.printStackTrace();
            return "error";
        }

    }

    @Override
    public List<OrUpdateExternalUser> addOrUpdateExternalUser1() {
        return baseMapper.addOrUpdateExternalUser1();
    }


    @Override
    public String token(String code,String state) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("client_id", "AIOERP");
        paramMap.put("grant_type", "authorization_code");
        paramMap.put("code", code);
        paramMap.put("state",state);
        paramMap.put("client_secret", "d4474b53a7204ad3888bd263a9f3617e");
        String url = "https://iam.funyard-hotels.com/idp/oauth2/getToken";
        String url2 = "https://iam.funyard-hotels.com/idp/oauth2/getUserInfo";
        String re = HttpUtil.post(url, paramMap);
        StaticLog.info("获取token,结果={}", re);
        JSONObject json = JSONUtil.parseObj(re);
        String access_token = json.getStr("access_token");
        HashMap<String, Object> paramMap2 = new HashMap<>();
        paramMap2.put("client_id", "AIOERP");
        paramMap2.put("access_token", access_token);
        String r2 = HttpUtil.get(url2, paramMap2);
        StaticLog.info("获取用户信息,结果222={}", r2);
        StaticLog.info("csssss={}", r2);
        int i = 0;
        Map obj = (Map) JSONUtil.parse(r2);
        StaticLog.info("插入数据库2{}", obj.get("displayName"));
        StaticLog.info("插入数据库3{}", null != obj.get("displayName"));
        if (null != obj.get("displayName")) {
            StaticLog.info("插入数据库", obj.get("displayName"));
            SyWorkstationLogin syWorkstationLogin = new SyWorkstationLogin();
            Map accessObj = (Map) JSONUtil.parse(re);
            String accessToken = String.valueOf(accessObj.get("access_token"));
            syWorkstationLogin.setAccess_token(accessToken);
            syWorkstationLogin.setBirthDay(String.valueOf(obj.get("birthDay")));
            syWorkstationLogin.setUpdateDate(String.valueOf(obj.get("updateDate")));
            syWorkstationLogin.setMail(String.valueOf(obj.get("mail")));
            syWorkstationLogin.setDisplayName(String.valueOf(obj.get("displayName")));
            syWorkstationLogin.setLoginInterceptFlagTwo(String.valueOf(obj.get("loginInterceptFlagTwo")));
            syWorkstationLogin.setLoginInterceptFlagFour(String.valueOf(obj.get("loginInterceptFlagFour")));
            syWorkstationLogin.setUid(String.valueOf(obj.get("uid")));
            syWorkstationLogin.setState(state);
            syWorkstationLogin.setCountry(String.valueOf(obj.get("country")));
            syWorkstationLogin.setGender(String.valueOf(obj.get("gender")));
            syWorkstationLogin.setLoginType(String.valueOf(obj.get("loginType")));
            syWorkstationLogin.setNation(String.valueOf(obj.get("nation")));
            syWorkstationLogin.setPositionNumber(String.valueOf(obj.get("positionNumber")));
            syWorkstationLogin.setTitle(String.valueOf(obj.get("title")));
            syWorkstationLogin.setChangePwdAt(String.valueOf(obj.get("changePwdAt")));
            syWorkstationLogin.setEmployeeNumber(String.valueOf(obj.get("employeeNumber")));
            syWorkstationLogin.setPwdPolicy(Integer.valueOf(String.valueOf(obj.get("pwdPolicy"))));
            syWorkstationLogin.setLoginInterceptFlagFive(Integer.valueOf(String.valueOf(obj.get("loginInterceptFlagFive"))));
            syWorkstationLogin.setLoginInterceptFlagThree(Integer.valueOf(String.valueOf(obj.get("loginInterceptFlagThree"))));
            syWorkstationLogin.setIdentityNumber(String.valueOf(obj.get("identityNumber")));
            syWorkstationLogin.setIdentityType(String.valueOf(obj.get("identityType")));
            syWorkstationLogin.setLoginName(String.valueOf(obj.get("loginName")));
            syWorkstationLogin.setSecAccValid(String.valueOf(obj.get("secAccValid")));
            syWorkstationLogin.setPinyinShortName(String.valueOf(obj.get("pinyinShortName")));
            syWorkstationLogin.setOrgNumber(String.valueOf(obj.get("orgNumber")));
            syWorkstationLogin.setWechatNo(String.valueOf(obj.get("wechatNo")));
            syWorkstationLogin.setOrgNamePath(String.valueOf(obj.get("orgNamePath")));
            syWorkstationLogin.setPasswordModifyRequired(Integer.valueOf(String.valueOf(obj.get("passwordModifyRequired"))));
            syWorkstationLogin.setGivenName(String.valueOf(obj.get("givenName")));
            syWorkstationLogin.setMobile(String.valueOf(obj.get("mobile")));
            syWorkstationLogin.setLoginInterceptFlagOne(Integer.valueOf(String.valueOf(obj.get("loginInterceptFlagOne"))));
            syWorkstationLogin.setCertSn(String.valueOf(obj.get("certSn")));
            syWorkstationLogin.setEmployeeType(String.valueOf(obj.get("employeeType")));
            syWorkstationLogin.setOrgCodePath(String.valueOf(obj.get("orgCodePath")));
            syWorkstationLogin.setOtpKey(String.valueOf(obj.get("otpKey")));
            syWorkstationLogin.setPositionStatus(String.valueOf(obj.get("positionStatus")));
            syWorkstationLogin.setDepartmentNumber(String.valueOf(obj.get("departmentNumber")));
            syWorkstationLogin.setCertDn(String.valueOf(obj.get("certDn")));
            syWorkstationLogin.setSpNameList(String.valueOf(obj.get("spNameList")));
            syWorkstationLogin.setIsPassRemind(Integer.valueOf(String.valueOf(obj.get("isPassRemind"))));
            i = baseMapper.insertSyWorkstationLoginMapper(syWorkstationLogin);
        }
        if (i > 0) {
            return "登录成功，关闭浏览器即可登陆";
        }
        return r2;


//        String result2 = HttpRequest.post(url)
//            .header("sign", "70F7ACCEBCA1227A3D6A888129E20CA6BF4FD3ED30C2B35CF293EB2EBAB22421")
//            .body(JSONUtil.toJsonStr(json))
//            .timeout(20000)//超时，毫秒
//            .execute().body();
    }

    @Override
    public String client() {
        try {
            String url = "https://open-api.bgy.com.cn/env-101/por-41902/movesapmdg/orchsym21996/DtSB/Sapmdm/Customer/ProxyServices/SapmdmCustomerImportSoapProxy";
            List<ErpMdgCustomer> listErpMdgCustomer = baseMapper.getListErpMdgCustomer();
            for (ErpMdgCustomer erpMdgCustomer : listErpMdgCustomer) {
                String xmlJSONObj1 = "<soapenv:Envelope \txmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
                    "\t<soap:Header \txmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
                    "\t</soap:Header>\n" +
                    "\t<soapenv:Body>\n" +
                    "\t<urn:ZfmBpCustomerCreate1 \txmlns:urn=\"urn:sap-com:document:sap:soap:functions:mc-style\">\n" +
                    "\t\t\t<IsEsbinfo>\n" +
                    "\t\t\t\t<Instid>"+IdUtil.simpleUUID()+"</Instid>\n" +
                    "\t\t\t\t<Requesttime>"+DateUtil.now()+"</Requesttime>\n" +
                    "\t\t\t\t<Attr1>bgy_ncmdm01</Attr1>\n" +
//            "\t\t\t\t<Attr2>string</Attr2>\n" +
//            "\t\t\t\t<Attr3>string</Attr3>\n" +
                    "\t\t\t</IsEsbinfo>\n" +
                    "\t\t\t<IsQueryinfo>\n" +
                    "\t\t\t\t<Pagesize>1</Pagesize>\n" +
                    "\t\t\t\t<Currentpage>1</Currentpage>\n" +
                    "\t\t\t</IsQueryinfo>\n" +
                    "\t\t\t<Requestinfo>\n" +
                    "\t\t\t\t<!--Zero or more repetitions:-->\n" +
                    "\t\t\t\t<item>\n" +
//                    "\t\t\t\t\t<Zkunnr>3000007056</Zkunnr>\n" +
//            "\t\t\t\t\t<Lifnr>string</Lifnr>\n" +
//            "\t\t\t\t\t<Zbackup1>string</Zbackup1>\n" +
//            "\t\t\t\t\t<Zbackup2>string</Zbackup2>\n" +
//            "\t\t\t\t\t<Zbackup3>string</Zbackup3>\n" +
//            "\t\t\t\t\t<Zbackup4>string</Zbackup4>\n" +
//            "\t\t\t\t\t<Zbackup5>string</Zbackup5>\n" +
//            "\t\t\t\t\t<Zhz>string</Zhz>\n" +
                    "\t\t\t\t\t<Zkhbk>"+erpMdgCustomer.getZKHBK()+"</Zkhbk>\n" +
                    "\t\t\t\t\t<Zktokd>"+erpMdgCustomer.getZKTOKD()+"</Zktokd>\n" +
                    "\t\t\t\t\t<Zland1>"+erpMdgCustomer.getZLAND1()+"</Zland1>\n" +
                    "\t\t\t\t\t<Zlyxt>"+erpMdgCustomer.getZLYXT()+"</Zlyxt>\n" +
                    "\t\t\t\t\t<Zname1>"+erpMdgCustomer.getZNAME1()+"</Zname1>\n" +
//            "\t\t\t\t\t<Zpmsbm>string</Zpmsbm>\n" +
//            "\t\t\t\t\t<Zrltyp>string</Zrltyp>\n" +
//            "\t\t\t\t\t<Zsapfrcd>stri</Zsapfrcd>\n" +
//            "\t\t\t\t\t<Zsapfrnm>string</Zsapfrnm>\n" +
//            "\t\t\t\t\t<Zsapzz>strin</Zsapzz>\n" +
                    "\t\t\t\t\t<Zsfz>"+erpMdgCustomer.getZSFZ()+"</Zsfz>\n" +
                    "\t\t\t\t\t<Zsgbm>"+erpMdgCustomer.getZSGBM()+"</Zsgbm>\n" +
//            "\t\t\t\t\t<Zspras>s</Zspras>\n" +
//            "\t\t\t\t\t<Zstceg>string</Zstceg>\n" +
                    "\t\t\t\t\t<Ztype>"+erpMdgCustomer.getZTYPE()+"</Ztype>\n" +
                    "\t\t\t\t\t<Zzxzfl>"+erpMdgCustomer.getZZXZFL()+"</Zzxzfl>\n" +
//            "\t\t\t\t\t<Returnstatus>string</Returnstatus>\n" +
//            "\t\t\t\t\t<Returncode>string</Returncode>\n" +
//            "\t\t\t\t\t<Returnmsg>string</Returnmsg>\n" +
                    "\t\t\t\t</item>\n" +
                    "\t\t\t</Requestinfo>\n" +
                    "\t\t</urn:ZfmBpCustomerCreate1>\n" +
                    "\t</soapenv:Body>\n" +
                    "</soapenv:Envelope>";
                String result2 = HttpRequest.post(url)
                    .header("sign", "70F7ACCEBCA1227A3D6A888129E20CA6BF4FD3ED30C2B35CF293EB2EBAB22421")
                    .body(xmlJSONObj1)
                    .header("Authorization","RVJQQUlPOkVSUGZ1bnlhcmRBSU8=")
                    .timeout(8000)//超时，毫秒
                    .execute().body();
                StaticLog.info("推送成功后的返回标识{}", result2);
//                JSONObject jsonObject=XML.toJSONObject(result2);
//                String request =jsonObject.getJSONObject("soapenv:Envelope").getJSONObject("soap:Header").getJSONObject("soapenv:Body").getJSONObject("urn:ZfmBpCustomerCreate1").toString();
//                System.out.println(request);
                int start=result2.indexOf("<Zkunnr>");
                int end=result2.indexOf("</Zkunnr>");
                String mdg=result2.substring(start+8,end);
                String customer=result2.substring(result2.indexOf("<Zlyxt>")+7,result2.indexOf("</Zlyxt>"));
                String taxId=result2.substring(result2.indexOf("<Zsfz>")+8,result2.indexOf("</Zsfz>"));
                System.out.println("mdg======"+mdg+"\ntaxId==========="+taxId+"\ncustomer=============="+customer);
                GlCustomer glCustomer=new GlCustomer();
                glCustomer.setMDG(mdg);
                glCustomer.setTaxId(taxId);
                glCustomer.setCustomer(customer);
                insertMDG(glCustomer);
                baseMapper.updateErpMdg(erpMdgCustomer.getCode());
                Thread.sleep(1000*10);
            }

            return "success";
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }


    }

    @Override
    public String selectMDG() {
        String url="https://openpre-api.bgy.com.cn/env-111/mdm-api/cnmdg/cnpoqas/search/vendor";
        JSONObject IS_OPTION =new JSONObject();
        IS_OPTION.put("PAGESIZE","2");
        IS_OPTION.put("CURRENTPAGE","1");
        JSONObject IS_ESBINFO =new JSONObject();
        IS_ESBINFO.put("ATTR1","BGY_TEST01");
        IS_ESBINFO.put("INSTID", IdUtil.simpleUUID());
        IS_ESBINFO.put("REQUESTTIME",DateUtil.now());
        JSONObject IS_REQUESTINFO=new JSONObject();
        IS_REQUESTINFO.put("ZZYGH","");
        IS_REQUESTINFO.put("ZZSTCD3","");
        IS_REQUESTINFO.put("ZZSTCEG","");
        IS_REQUESTINFO.put("NAME_ORG1","德勤*");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("IS_OPTION", IS_OPTION);
        jsonObject.put("IS_ESBINFO", IS_ESBINFO);
        jsonObject.put("IS_REQUESTINFO", IS_REQUESTINFO);
        String result2 = HttpRequest.post(url)
            .header("sign", "70F7ACCEBCA1227A3D6A888129E20CA6BF4FD3ED30C2B35CF293EB2EBAB22421")
            .body(String.valueOf(jsonObject))
            .header("APIKey","8KU0JMgFigrvEuhrdirVJxjkelRkbllN")
            .timeout(2000)//超时，毫秒
            .execute().body();
        StaticLog.info("成功后的返回标识{}", result2);
        return result2;
    }

    @Override
    public int updateSySupplier(String MDG, String TaxId) {
        return baseMapper.updateSySupplier(MDG,TaxId);
    }

    @Override
    public int insertSySupplier(String Supplier, String TaxId, String Active, String InsertTime, String MDG,String Mail,String Phone,String Address,String Contact) {
        return baseMapper.insertSySupplier(Supplier, TaxId, Active, InsertTime,MDG,Mail,Phone,Address,Contact);
    }


//    @Override
//    public int insertSySupplier(ClientCallBackBo clientCallBackBo) {
//        return baseMapper.insertSySupplier(clientCallBackBo);
//    }


//    @Override
//    public int insertSySupplier(Map<String, Object> insertClientCallBackBo) {
//        return baseMapper.insertSySupplier(insertClientCallBackBo);
//    }

    @Override
    public int getByClientCallBackBo(String TaxId) {
        return baseMapper.getByClientCallBackBo(TaxId);
    }

    @Override
    public List<ErpMdgCustomer> getListErpMdgCustomer() {
        return baseMapper.getListErpMdgCustomer();
    }

    @Override
    public int updateErpMdg(String RetCode) {
        return baseMapper.updateErpMdg(RetCode);
    }

    @Override
    public int insertErpMdg(ErpMdgCustomer erpMdgCustomer) {
        return baseMapper.insertErpMdg(erpMdgCustomer);
    }

    @Override
    public int getByRetCode(String RetCode) {
        return baseMapper.getByRetCode(RetCode);
    }

    @Override
    public int updateMDG(String MDG) {
        return 0;
    }

    @Override
    public int insertMDG(GlCustomer glCustomer) {
        return baseMapper.insertMDG(glCustomer);
    }

    @Override
    public int insertBank(SysBank sysBank) {
        return baseMapper.insertBank(sysBank);
    }

    @Override
    public String selectDescription(String Code, String Description) {
        return baseMapper.selectDescription(Code, Description);
    }

    @Override
    public int insertBankCard(BankCreditCard bankCreditCard) {
        return baseMapper.insertBankCard(bankCreditCard);
    }

    @Override
    public int deleteBank(String BankTrxCode) {
        return baseMapper.deleteBank(BankTrxCode);
    }

    @Override
    public int deleteBankCard(String Code) {
        return baseMapper.deleteBankCard(Code);
    }

    @Override
    public int updateBankCard(String VoucherNo,String BankTrxCode) {
        return baseMapper.updateBankCard(VoucherNo,BankTrxCode);
    }

    @Override
    public int updateBankReam(String Remark, String BankTrxCode) {
        return baseMapper.updateBankReam(Remark, BankTrxCode);
    }

    @Override
    public BankCreditCard getBankCreditCard(String MISNO) {
        return baseMapper.getBankCreditCard(MISNO);
    }

    @Override
    public List<String> getrvPaymentTypeAll() {
        List<String> list = new ArrayList<>();
        List<rvPaymentType> activeCodeInfos = baseMapper.getrvPaymentTypeAll();
        for (int i = 0; i < activeCodeInfos.size(); i++) {
            String active_code = activeCodeInfos.get(i).getActive();
            list.add(active_code);
        }
        return list;
    }

    @Override
    public String addGlOrUpdateOrganization() {
        String url = "https://iam.funyard-hotels.com/hotelService/organization/addOrModifyOrganization";
        try {
            List<addOrUpdateOrganization> select = baseMapper.addOrUpdateOrganization();
            for (addOrUpdateOrganization addOrUpdateOrganization : select) {
                List<addOrUpdateOrganization> list = new ArrayList();
                list.add(addOrUpdateOrganization);
                IS_ESBINFO isEsbinfo = new IS_ESBINFO();
                isEsbinfo.setINSTID(IdUtil.simpleUUID());
                isEsbinfo.setREQUESTTIME(DateUtil.now());
                isEsbinfo.setATTR3("BC_FYAIO");
                Map map = new HashMap();
                map.put("IS_ESBINFO", isEsbinfo);
                map.put("REQUESTINFO", list);
                Console.log("请求参数:{}",JSONUtil.toJsonStr(map));
                String json = JSONUtil.toJsonStr(map);
                String result2 = HttpRequest.post(url)
                    .header("sign", "120477CF4AB2A6044099ED007E483259BF4FD3ED30C2B35CF293EB2EBAB22421")
                    .body(JSONUtil.toJsonStr(json))
                    .timeout(200000)//超时，毫秒
                    .execute().body();
                Console.log("响应参数:{}", result2);
                baseMapper.GlAddOrUpdateOrganizationUpdate(addOrUpdateOrganization.getZORG(),JSONUtil.toJsonStr(map),result2);
                Thread.sleep(1000*1);


            }

            return "success";
        }catch(Exception e){
            e.printStackTrace();
            return "error";
        }
    }

    @Override
    public List<addOrUpdateOrganization> addOrUpdateOrganization() {
        return baseMapper.addOrUpdateOrganization();
    }


    @Override
    public List<FtTransactionCode> getFtTransactionCodeAll() {
        return baseMapper.getFtTransactionCodeAll();
    }

    @Override
    public int InsertSyUserLog(SyUserLog syUserLog) {
        return baseMapper.InsertSyUserLog(syUserLog);
    }


//    @Override
//    public void clientCallBack(ClientCallBackBo bo) {
//        //对方回调更新数据库，把这条数据更新为已推送成功，自己写sql语句更新，
////        int i = baseMapper.insertSyWorkstationLoginMapper(syWorkstationLogin);
////        if (i > 0) {
////            //成功
////            return;
////        }
//    }



    public static void main1(String[] args) {
//        //数据库查出来数据推送给对方
        String url = "https://opentest-api.bgy.com.cn/env-101/por-23178/movesapmdg/orchsym21996/DtSB/Sapmdm/Customer/ProxyServices/SapmdmCustomerImportSoapProxy";
//
//        // 创建 IsEsbinfo 对象
//        JSONObject isEsbinfo = new JSONObject();
//        isEsbinfo.put("Instid", IdUtil.simpleUUID());
//        isEsbinfo.put("Requesttime", DateUtil.now());
//        isEsbinfo.put("Attr1", "Attr13");
//        isEsbinfo.put("Attr2", "Attr24");
//        isEsbinfo.put("Attr3", "Attr35");
//
//        // 创建 IsQueryinfo 对象
//        JSONObject isQueryinfo = new JSONObject();
//        isQueryinfo.put("Pagesize", "Pagesize6");
//        isQueryinfo.put("Currentpage", "Currentpage7");
//
//        // 创建 Requestinfo 对象
//        JSONObject requestinfo = new JSONObject();
//        JSONArray itemArray = new JSONArray();
//
//        JSONObject item = new JSONObject();
//        item.put("Zkunnr", "string8");
//        item.put("Lifnr", "string10");
//        item.put("Zbackup1", "string12");
//        item.put("Zbackup2", "string14");
//        item.put("Zbackup3", "string16");
//        item.put("Zbackup4", "string18");
//        item.put("Zbackup5", "string20");
//        item.put("Zhz", "string22");
//        item.put("Zkhbk", "string24");
//        item.put("Zktokd", "stri");
//        item.put("Zland1", "str");
//        item.put("Zlyxt", "string30");
//        item.put("Zname1", "string32");
//        item.put("Zpmsbm", "string34");
//        item.put("Zrltyp", "string");
//        item.put("Zsapfrcd", "stri");
//        item.put("Zsapfrnm", "string40");
//        item.put("Zsapzz", "strin");
//        item.put("Zsfz", "string44");
//        item.put("Zsgbm", "string46");
//        item.put("Zspras", "s");
//        item.put("Zstceg", "string50");
//        item.put("Ztype", "s");
//        item.put("Zzxzfl", "st");
//        item.put("Returnstatus", "string56");
//        item.put("Returncode", "string58");
//        item.put("Returnmsg", "string60");
//
//        itemArray.put(item);
//        requestinfo.put("item", itemArray);
//
//        // 创建最终的 JSON 对象
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("IsEsbinfo", isEsbinfo);
//        jsonObject.put("IsQueryinfo", isQueryinfo);
//        jsonObject.put("Requestinfo", requestinfo);


        // 将 JSON 对象转换成字符串并输出
//        String xmlJSONObj = JSONUtil.toXmlStr(jsonObject);
        String xmlJSONObj = "<soapenv:Envelope \txmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
            "\t<soap:Header \txmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
            "\t</soap:Header>\n" +
            "\t<soapenv:Body>\n" +
            "\t<urn:ZfmBpCustomerCreate1 \txmlns:urn=\"urn:sap-com:document:sap:soap:functions:mc-style\">\n" +
            "\t\t\t<IsEsbinfo>\n" +
            "\t\t\t\t<Instid>02e06a56-2fc3-4674-b373-069ef7422de1</Instid>\n" +
            "\t\t\t\t<Requesttime>string</Requesttime>\n" +
            "\t\t\t\t<Attr1>bgy_ncmdm01</Attr1>\n" +
//            "\t\t\t\t<Attr2>string</Attr2>\n" +
//            "\t\t\t\t<Attr3>string</Attr3>\n" +
            "\t\t\t</IsEsbinfo>\n" +
            "\t\t\t<IsQueryinfo>\n" +
            "\t\t\t\t<Pagesize>string</Pagesize>\n" +
            "\t\t\t\t<Currentpage>string</Currentpage>\n" +
            "\t\t\t</IsQueryinfo>\n" +
            "\t\t\t<Requestinfo>\n" +
            "\t\t\t\t<!--Zero or more repetitions:-->\n" +
            "\t\t\t\t<item>\n" +
            "\t\t\t\t\t<Zkunnr>string</Zkunnr>\n" +
            "\t\t\t\t\t<Lifnr>string</Lifnr>\n" +
//            "\t\t\t\t\t<Zbackup1>string</Zbackup1>\n" +
//            "\t\t\t\t\t<Zbackup2>string</Zbackup2>\n" +
//            "\t\t\t\t\t<Zbackup3>string</Zbackup3>\n" +
//            "\t\t\t\t\t<Zbackup4>string</Zbackup4>\n" +
//            "\t\t\t\t\t<Zbackup5>string</Zbackup5>\n" +
//            "\t\t\t\t\t<Zhz>string</Zhz>\n" +
            "\t\t\t\t\t<Zkhbk>1</Zkhbk>\n" +
            "\t\t\t\t\t<Zktokd>K003</Zktokd>\n" +
            "\t\t\t\t\t<Zland1>CN</Zland1>\n" +
            "\t\t\t\t\t<Zlyxt>BGY_CAMS03</Zlyxt>\n" +
            "\t\t\t\t\t<Zname1>彭权</Zname1>\n" +
//            "\t\t\t\t\t<Zpmsbm>string</Zpmsbm>\n" +
//            "\t\t\t\t\t<Zrltyp>string</Zrltyp>\n" +
//            "\t\t\t\t\t<Zsapfrcd>stri</Zsapfrcd>\n" +
//            "\t\t\t\t\t<Zsapfrnm>string</Zsapfrnm>\n" +
//            "\t\t\t\t\t<Zsapzz>strin</Zsapzz>\n" +
            "\t\t\t\t\t<Zsfz>429001199003186461</Zsfz>\n" +
            "\t\t\t\t\t<Zsgbm>10010320</Zsgbm>\n" +
//            "\t\t\t\t\t<Zspras>s</Zspras>\n" +
//            "\t\t\t\t\t<Zstceg>string</Zstceg>\n" +
            "\t\t\t\t\t<Ztype>2</Ztype>\n" +
            "\t\t\t\t\t<Zzxzfl>10</Zzxzfl>\n" +
//            "\t\t\t\t\t<Returnstatus>string</Returnstatus>\n" +
//            "\t\t\t\t\t<Returncode>string</Returncode>\n" +
//            "\t\t\t\t\t<Returnmsg>string</Returnmsg>\n" +
            "\t\t\t\t</item>\n" +
            "\t\t\t</Requestinfo>\n" +
            "\t\t</urn:ZfmBpCustomerCreate1>\n" +
            "\t</soapenv:Body>\n" +
            "</soapenv:Envelope>";

        String result2 = HttpRequest.post(url)
            .header("sign", "70F7ACCEBCA1227A3D6A888129E20CA6BF4FD3ED30C2B35CF293EB2EBAB22421")
            .body(xmlJSONObj)
            .header("Authorization","QWRtaW46MTIzNA==")
            .timeout(2000)//超时，毫秒
            .execute().body();
        StaticLog.info("推送成功后的返回标识{}", result2);
    }



}
